package dao.caminhoneiro;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import entidade.caminhoneiro.Caminhoneiro;
import entidade.caminhoneiro.Lance;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import apresentacao.caminhoneiro.Activity_Menu_Principal;

// Abre uma nova thread para n�o deixar o aplicativo pesado e faz a inser��o do novo caminhoneiro
public class AsyncTask_Novo_Lance extends AsyncTask<Void, Void, String>{
	private ProgressDialog progress;
	Context context;
	Lance lance;
	public AsyncTask_Novo_Lance(Lance lance, Context context) {
		this.context = context;
		this.lance = lance;
	}
	
	@Override
	protected String doInBackground(Void... params) {
		try {
			final String URL = "http://nome-produtor.rhcloud.com/novo_lance/";
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(URL);
			List<NameValuePair> param = new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("id_frete", 		Integer.toString(lance.getFrete().getId())));
			param.add(new BasicNameValuePair("id_produtor", 	Integer.toString(lance.getFrete().getProdutor().getId())));
			param.add(new BasicNameValuePair("preco", 			Float.toString(lance.getPreco())));
			param.add(new BasicNameValuePair("id_caminhoneiro", Integer.toString(Activity_Menu_Principal.user_id)));
		    post.setEntity(new UrlEncodedFormEntity(param));
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			String line = rd.readLine();
			return line;
		} catch (Exception e) {
			return e.toString();
		}
	}
	
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		progress.dismiss();
		if(result.equals("OK")){
			Toast.makeText(context, "Lance enviado!", Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		progress = ProgressDialog.show(context, "Concorrer", "Em progresso...");
				
	}
}
